package com.czy.owner.ui.login;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.EdtCheckEntity;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.MainActivity;
import com.czy.owner.utils.ActivityHelper;
import com.czy.owner.utils.GetDeviceId;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.zxing.library.CaptureActivity;
import com.zxing.library.ZXingConstants;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.x;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/5/23.
 * 注册
 */
@ContentView(R.layout.activity_regist)
public class RegistActivity extends BaseActivity {
    @BindView(R.id.et_regist_phone)
    EditText etRegistPhone;
    @BindView(R.id.et_regist_psd)
    EditText etRegistPasssword;
    @BindView(R.id.et_regist_psd_again)
    EditText etRegistPassswordAgain;
    @BindView(R.id.et_regist_yanzhengma)
    EditText etRegistCode;
    @BindView(R.id.tv_regist_get_yanzhengma)
    TextView tvRegistGetCode;
    @BindView(R.id.et_regist_fuwuhao)
    EditText etRegistServiceNumber;
    @BindView(R.id.btn_now_regist)
    Button btnNowRegist;
    @BindView(R.id.cb_regist)
    CheckBox cbRegist;
    private boolean ischeck = true;
    private String storeId;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_regist;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.regist);
        getSubTitle().setText(R.string.login);
        etRegistPhone.addTextChangedListener(new NewWatcher());
        etRegistPasssword.addTextChangedListener(new NewWatcher());
        etRegistPassswordAgain.addTextChangedListener(new NewWatcher());
        etRegistCode.addTextChangedListener(new NewWatcher());
    }

    @Override
    protected void updateViews() {

    }


    public class NewWatcher implements TextWatcher {

        private boolean check = false, check_ = true;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (s.length() > 0) {
                check = true;
            } else if (s.length() == 0) {
                check_ = true;
                check = false;
            }

            if (check) {
                if (check_) {
                    EdtCheckEntity.checkNum++;
                    check_ = false;
                    if (EdtCheckEntity.checkNum == 4 && ischeck) {
                        btnNowRegist.setEnabled(true);
                        btnNowRegist.setBackgroundResource(R.drawable.selector_login_btn_commit);
                    }
                }
            } else {
                EdtCheckEntity.checkNum--;
                if (EdtCheckEntity.checkNum < 4) {
                    btnNowRegist.setEnabled(false);
                    btnNowRegist.setBackgroundResource(R.drawable.selector_no_register_btn);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

    }


    //获取验证码
    @OnClick(R.id.tv_regist_get_yanzhengma)
    public void tvRegistGetCodeOnClick(View view) {
        if (!PhoneUtils.isNetworkConnected(RegistActivity.this)) {
            return;
        }
        String phone = etRegistPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            PhoneUtils.ShowToastMessage(RegistActivity.this, getString(R.string.phone_error_null));
            return;
        }
        if (!PhoneUtils.isMobileNO(phone)) {//本地验证手机格式
            PhoneUtils.ShowToastMessage(RegistActivity.this, getString(R.string.phone_error));
            return;
        }

        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.REGIST_REQSMSCODE_API);
        params.addBodyParameter("phone", phone);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    timer.start();
                } else {
                    PhoneUtils.ShowToastMessage(RegistActivity.this, exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }


    //    立即注册
    @OnClick(R.id.btn_now_regist)
    public void btnNowRegistOnClick(View view) {
        final String phone = etRegistPhone.getText().toString().trim();
        final String password = etRegistPasssword.getText().toString().trim();
        final String passwordagain = etRegistPassswordAgain.getText().toString().trim();
        String code = etRegistCode.getText().toString().trim();
        final String serviceNumber = etRegistServiceNumber.getText().toString().trim();


        if (!PhoneUtils.isNetworkConnected(RegistActivity.this)) {
            return;
        }
        if (!PhoneUtils.isMobileNO(phone)) {
            PhoneUtils.ShowToastMessage(RegistActivity.this, getString(R.string.phone_error));
            etRegistPhone.requestFocus();
            return;
        }


        if (password.length() < 6 || password.length() > 20) {
            PhoneUtils.ShowToastMessage(RegistActivity.this, getString(R.string.input_psd_length));
            etRegistPasssword.requestFocus();
            return;
        }

        if (!password.equals(passwordagain)) {
            PhoneUtils.ShowToastMessage(RegistActivity.this, getString(R.string.twice_password_disagree));
            etRegistPassswordAgain.requestFocus();
            return;
        }

        if ((Build.VERSION.SDK_INT >= 23)) {
            phoneStatePermissions(phone, password, code, serviceNumber);
        } else {
            GetDeviceId getDeviceId = new GetDeviceId(RegistActivity.this);
            pid = getDeviceId.getCombinedId();
            MyLog.e("yang", "注册pid==" + pid);
            UserRegistApi(phone, password, code, serviceNumber);
        }


    }

    public String pid = "";

    public void phoneStatePermissions(final String phone, final String password, final String code, final String serviceNumber) {
        Acp.getInstance(RegistActivity.this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.READ_PHONE_STATE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        GetDeviceId getDeviceId = new GetDeviceId(RegistActivity.this);
                        pid = getDeviceId.getCombinedId();
                        MyLog.e("yang", "注册pid==" + pid);
                        UserRegistApi(phone, password, code, serviceNumber);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(RegistActivity.this, "获取手机权限拒绝");

                    }
                });
    }


    private void UserRegistApi(final String phone, final String password, final String code, final String storeId) {
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.REGIST_API);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("password", password);
        params.addBodyParameter("smsCode", code);
        params.addBodyParameter("storeId", storeId);
        params.addBodyParameter("pid", pid);
        mLoadView.ShowLoadView();
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {//判断调用注册接口是否成功,直接调用登录接口进入MainAcitivy
                    SharedPreferencesUtils.setParam(RegistActivity.this, Constants.SHARED_PREFERENCES_KEY_PHONE, phone);
                    PhoneUtils.ShowToastMessage(RegistActivity.this,"注册成功");
                    intoMainActivity(phone, password);
                } else {//注册接口错误提示
                    PhoneUtils.ShowToastMessage(RegistActivity.this, exp);
                }
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                PhoneUtils.ShowToastMessage(RegistActivity.this, getString(R.string.connect_service_error));
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //注册成功后调用登录接口进入MainActivity
    private void intoMainActivity(final String phone, final String password) {
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.LOGIN_API);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("password", password);
        params.addBodyParameter("consoleType", "mob");
        params.addBodyParameter("consoleSubType", "androidOwn");
        params.addBodyParameter("pid", pid);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "result==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    // 直接登录
                    String data = JsonUtil.getJsonValuesString(result, "data");
                    UserHelper.getInstance().saveUserAuth(phone, password, true);
                    UserHelper.getInstance().saveUserInfo(RegistActivity.this, data);
                    UserHelper.getInstance().setIsLogined(true);
//                    ActivityHelper.getInstance().finishAllActivity();
                    MessageHelper.getInstance().reset();
                    EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(RegistActivity.this).getImKey(), UserHelper.getInstance().getUserInfoModel(RegistActivity.this).getImPasswd(), new EMCallBack() {//回调
                        @Override
                        public void onSuccess() {
                            MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getNickName(),
                                    UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getUserLogo());

                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                            MyLog.d("King", "登录聊天服务器成功！");
                            ActivityHelper.getInstance().finishAllActivity();
                            startActivity(new Intent(RegistActivity.this, MainActivity.class));
                        }

                        @Override
                        public void onProgress(int progress, String status) {

                        }

                        @Override
                        public void onError(int code, String message) {
                            MyLog.d("King", "登录聊天服务器失败！" + code + "|" + message);
                            ActivityHelper.getInstance().finishAllActivity();
                            startActivity(new Intent(RegistActivity.this, MainActivity.class));
                        }
                    });
                } else {
                    PhoneUtils.ShowToastMessage(RegistActivity.this, exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                PhoneUtils.ShowToastMessage(RegistActivity.this, getString(R.string.connect_service_error));
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //二维码扫码
    @OnClick(R.id.img_saoyisao)
    public void imgZxingOnClick(View view) {
        if ((Build.VERSION.SDK_INT >= 23)) {
            onClicCamera();
        } else {
            Intent intent = new Intent(RegistActivity.this, CaptureActivity.class);
            startActivityForResult(intent, ZXingConstants.ScanRequestCode);
        }

    }

    //6.0系统打开相机
    public void onClicCamera() {
        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.CAMERA).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(RegistActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, ZXingConstants.ScanRequestCode);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(RegistActivity.this, permissions.toString() + "权限拒绝");
                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            PhoneUtils.ShowToastMessage(RegistActivity.this, "请扫描袋鼠店管家门店二维码");
            return;
        }
        switch (requestCode) {
            case ZXingConstants.ScanRequestCode:
                if (resultCode == ZXingConstants.ScanRequestCode) {
                    String result = data.getStringExtra(ZXingConstants.ScanResult);
                    try {
                        String[] spStr = result.split("=");
                        storeId = spStr[1];
                        etRegistServiceNumber.setText(storeId);
                    } catch (Exception e) {
                        PhoneUtils.ShowToastMessage(RegistActivity.this, "请扫描袋鼠店管家门店二维码");
                    }


                }

                break;
        }
    }

    @OnClick(R.id.cb_regist)
    public void cbRegistOnClick(View view) {
        ischeck = cbRegist.isChecked();
        if (ischeck && EdtCheckEntity.checkNum == 4) {
            btnNowRegist.setEnabled(true);
            btnNowRegist.setBackgroundResource(R.drawable.selector_login_btn_commit);
        } else {
            btnNowRegist.setEnabled(false);
            btnNowRegist.setBackgroundResource(R.drawable.selector_no_register_btn);
        }


    }

    @OnClick(R.id.toolbar_subtitle)
    public void login(View view) {
        finish();
    }

    //   倒计时响应事件  timer.start();
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvRegistGetCode.setClickable(false);// 设置不能点击
            tvRegistGetCode.setText(millisUntilFinished / 1000 + getString(R.string.send_again));// 设置倒计时时间
            tvRegistGetCode.setTextColor(getResources().getColor(R.color.appTipColor)); // 设置为灰色，这时是不能点击的
        }

        @Override
        public void onFinish() {
            tvRegistGetCode.setText(getResources().getString(R.string.get_yanzhengma));
            tvRegistGetCode.setClickable(true);// 重新获得点击
            tvRegistGetCode.setTextColor(getResources().getColor(R.color.appThemeColor));

        }
    };

    @OnClick(R.id.tv_regist_xieyi)
    public void tvRegistAgreementOnClick(View view) {
        Intent ti = new Intent(RegistActivity.this, AgreeMentActivity.class);
        startActivity(ti);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EdtCheckEntity.checkNum = 0;
    }
}
